<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

class TestPaperController extends AdminbaseController{
    protected $paper_model;
    protected $ques_model;
    protected $term_relationships_model;
    protected $terms_model;

    protected $question_opts=array("1"=>"A","2"=>"B","3"=>"C","4"=>"D","5"=>"E","6"=>"F");
    protected $question_types=array("1"=>"单选题","2"=>"多项选择题","3"=>"填空题","4"=>"判断题","5"=>"主观题");
    protected $type_control=array("1"=>"radio","2"=>"checkbox","3"=>"","4"=>"radio","5"=>"");
    protected $option_count=array("2","3","4","5","6");
    
	public function _initialize() {
		parent::_initialize();
		$this->test_paper_model = D("Admin/TestPaper");
		$this->paper_model = D("Admin/Paper");
		$this->ques_model = D("Admin/Questions");
		$this->terms_model = D("Portal/QuesTerms");
		$this->term_relationships_model = D("Portal/QuesTermRelationships");
		$this->assign("question_types",$this->question_types);
		$this->assign("question_opts",$this->question_opts);
		$this->assign("option_count",$this->option_count);
	}
    
    // 后台考题管理列表
    public function paper($paper_type){

        $id=I('id',0,'intval');
        $term_id=I('term_id',0,'intval');
        //$paper_type=I('paper_type',0,'intval');
        $keyword=I('keyword');
       
		$map=null;
		if($id>0) $map['a.id']=$id;
		if($term_id>0) $map['a.paper_term']=$term_id;
		$map['a.paper_type']=$paper_type;
		if(!empty($keyword)) $map['a.paper_name']=$keyword;
		if(isset($map))$map['_logic']='AND';
        $this->_lists($map);
        $this->_getTree();

        $paper_terms=array();
        $terms=$this->terms_model->select();        
        foreach ($terms as $term){
            $paper_terms[$term['term_id']]=$term['name'];
        }

        $this->assign("id",$id==0?'':$id);
        $this->assign("term_id",$term_id);
        $this->assign("keyword",$keyword);
		$this->assign("paper_terms",$paper_terms);
    }
    public function index($paper_type=1){
        $this->paper($paper_type);
        $this->assign("paper_type",$paper_type);
        $this->display('index');
    }
    
    /**
     * 默认显示模拟考试的信息
     */
    public function simulate(){
        $this->paper(0);
        $this->assign("paper_type",0);
        $this->display('index');
    }
    /**
     * 试卷预览
     * @param unknown $id
     */
    public function review($id){
        $paper=$this->paper_model->find($id);
        $paper_setting=unserialize($paper['paper_setting']);
        $ques_type_lite_arr=$paper_setting['questypelite'];
        $ques_type_arr=$paper_setting['questype'];
        
        $ques_list_arr_tmp=Array();
        foreach ($ques_type_arr as $ques_list){
            empty($ques_list['ques_list'])||$ques_list_arr_tmp[]=$ques_list['ques_list'];
        }
        $ques_list_sting=implode(',', $ques_list_arr_tmp);
        $map['id'] = array('in',explode(',', $ques_list_sting));
        $ques_list_data=$this->ques_model->where($map)->order("find_in_set(id,'$ques_list_sting')")->select();
        //echo $this->ques_model->getLastSql(); 
        //var_dump($this->ques_model->getLastSql());
        $this->assign('ques_type_lite_arr',$ques_type_lite_arr);
        $this->assign('ques_type_arr',$ques_type_arr);
        $this->assign('paper_setting',$paper_setting);
        $this->assign('paper',$paper);
        $this->assign('ques_list',$ques_list_data);
        $this->display();
    }
    
    // 文章添加
    public function add($paper_type=0){
        $terms = $this->terms_model->order(array("listorder"=>"asc"))->select();
        $term_id = I("get.term",0,'intval');
        $this->_getTermTree();
        $term=$this->terms_model->where(array('term_id'=>$term_id))->find();
        $this->assign("term",$term);
        $this->assign("terms",$terms);
        $this->assign("paper_type",$paper_type);
        $this->display();
    }
    
    // 文章添加提交
    public function add_paper(){
        if (IS_POST) {
            if(empty($_POST['paper_name'])){
                $this->error("请填写试卷名称！");
            }
            $count=$this->paper_model->where('paper_name=%s',$_POST['paper_name'])->count();
            if($count){
                $this->error("试卷名称已存在，请修改后重试！");
            }
            if(empty($_POST['paper_term'])){
                $this->error("请至少选择一个分类！");
            }
            if(empty($_POST['paper_score'])){
                $this->error("请填写试卷总分！");
            }
            if(empty($_POST['paper_pass_score'])){
                $this->error("请填写通过分数！");
            }
            $data['paper_name']=I("paper_name");
            
            
            $data['paper_type']=I("paper_type");
            $data['paper_term']=I("paper_term",0,'intval');
            $data['paper_judge_type']=I("paper_judge_type",0,'intval');
            $data['paper_choose_type']=I("paper_choose_type",0,'intval');
                        
            $data['paper_status']=I("paper_status",0,'intval');
            $start_time_array=I("paper_start_time");
            $date=strtotime($start_time_array['day']);
            $start_time=mktime($start_time_array['hour'],$start_time_array['min'],0,date('m',$date),date('d',$date),date('Y',$date));
            //$data['paper_start_time']=date('Y-m-d h:i:s',$start_time);
            //$data['paper_duration']=I("paper_duration",0,'intval');
            $data['paper_score']=I("paper_score",0,'intval');
            $data['paper_pass_score']=I("paper_guide",0);
            $paper_setting=is_array(I("paper_setting"))?I("paper_setting"):I("paper_setting");
            $data['listorder']=I("listorder",0,'intval');
            $data['paper_source']=I("paper_source",0);
            $data['paper_modified']=date("Y-m-d H:i:s",time());
            $data['user_id']=get_current_admin_id();
            
            $data['paper_score']||$this->error('试卷总分不能为0，请认真填写 ！');
            
            $full_score=0;
            foreach ($this->question_types as $key=>$type){
                $full_score+=$paper_setting['questype'][$key]['number']*$paper_setting['questype'][$key]['score'];
                //$data['paper_setting']['questype'][$key]['describe']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$key]['easynumber']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$key]['middlenumber']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$key]['hardnumber']||$this->error('请填写'.$type.'数量！');
            }
            $full_score!=$data['paper_score']&&$this->error('题目设置分数与总分不一致，请认真填写 ！');
            
            //根据选题方式生成试卷题目
            /* if($data['paper_choose_type']==0){
                //随机选题
                foreach ($this->question_types as $ques_type=>$ques_type_name){
                    //总题目数量
                    $number= $paper_setting['questype'][$ques_type]['number'];
                    //简单题目数量
                    $easynumber= $data['paper_setting']['questype'][$ques_type]['easynumber'];
                    $middlenumber= $data['paper_setting']['questype'][$ques_type]['middlenumber'];
                    $hardnumber= $data['paper_setting']['questype'][$ques_type]['hardnumber'];
                    if($easynumber+$middlenumber+$hardnumber==0){
                        //全随机模式
                        $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0",$data['paper_term'],$ques_type)->order('RAND()')->limit($number)->select();
                        $ques_list_rnd_arr=array();
                        foreach($ques_list_rnd as $ques_item_data){
                            $ques_list_rnd_arr[]=$ques_item_data['id'];
                        }
                        $paper_setting['questype'][$ques_type]['ques_list']=implode(',',$ques_list_rnd_arr);
                    }
                    else if($easynumber+$middlenumber+$hardnumber==$number){
                        $ques_list_rnd_arr=array();
                        //按难易程度随机
                        if($easynumber>0){
                            $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,1)->order('RAND()')->limit($easynumber)->select();
                            foreach($ques_list_rnd as $ques_item_data){
                                $ques_list_rnd_arr[]=$ques_item_data['id'];
                            }
                        }
                        if($middlenumber>0){
                            $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,2)->order('RAND()')->limit($middlenumber)->select();
                            foreach($ques_list_rnd as $ques_item_data){
                                $ques_list_rnd_arr[]=$ques_item_data['id'];
                            }
                        }
                        if($hardnumber>0){
                            $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,3)->order('RAND()')->limit($hardnumber)->select();
                            foreach($ques_list_rnd as $ques_item_data){
                                $ques_list_rnd_arr[]=$ques_item_data['id'];
                            }
                        }
                        $paper_setting['questype'][$ques_type]['ques_list']=implode(',',$ques_list_rnd_arr);
                    }
                    else{
                        $this->error('['.$ques_type_name.']总题目数量与难易设置数量不一致，请认真填写！');
                    }
                }
            }
             */
            
            //var_dump($paper_setting);
            //序列化
            $data['paper_setting']=serialize($paper_setting);
            $result=$this->paper_model->add($data);
            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }
        }
    }
    /**
     * 根据试卷设置生成试卷
     * @param unknown $id
     */
    public function generate_paper($id){
        $data=$this->paper_model->find($id);  
        $paper_setting=unserialize($data['paper_setting']);
        if($data['paper_choose_type']==0){
            //随机选题
            foreach ($this->question_types as $ques_type=>$ques_type_name){
                //总题目数量
                $number= $paper_setting['questype'][$ques_type]['number'];
                //简单题目数量
                $easynumber= $data['paper_setting']['questype'][$ques_type]['easynumber'];
                $middlenumber= $data['paper_setting']['questype'][$ques_type]['middlenumber'];
                $hardnumber= $data['paper_setting']['questype'][$ques_type]['hardnumber'];
                if($easynumber+$middlenumber+$hardnumber==0){
                    //全随机模式
                    $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0",$data['paper_term'],$ques_type)->order('RAND()')->limit($number)->select();
                    $ques_list_rnd_arr=array();
                    foreach($ques_list_rnd as $ques_item_data){
                        $ques_list_rnd_arr[]=$ques_item_data['id'];
                    }
                    $paper_setting['questype'][$ques_type]['ques_list']=implode(',',$ques_list_rnd_arr);
                }
                else if($easynumber+$middlenumber+$hardnumber==$number){
                    $ques_list_rnd_arr=array();
                    //按难易程度随机
                    if($easynumber>0){
                        $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,1)->order('RAND()')->limit($easynumber)->select();
                        foreach($ques_list_rnd as $ques_item_data){
                            $ques_list_rnd_arr[]=$ques_item_data['id'];
                        }
                    }
                    if($middlenumber>0){
                        $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,2)->order('RAND()')->limit($middlenumber)->select();
                        foreach($ques_list_rnd as $ques_item_data){
                            $ques_list_rnd_arr[]=$ques_item_data['id'];
                        }
                    }
                    if($hardnumber>0){
                        $ques_list_rnd=$this->ques_model->field("id")->where("ques_term='%s' and ques_type=%d and ques_status=0 and ques_level=%d",$data['paper_term'],$ques_type,3)->order('RAND()')->limit($hardnumber)->select();
                        foreach($ques_list_rnd as $ques_item_data){
                            $ques_list_rnd_arr[]=$ques_item_data['id'];
                        }
                    }
                    $paper_setting['questype'][$ques_type]['ques_list']=implode(',',$ques_list_rnd_arr);
                }
                else{
                    $this->error('['.$ques_type_name.']总题目数量与难易设置数量不一致，请认真填写！');
                }
            }
        }
    }    
    
    // 文章编辑
    public function edit(){
        $id=  I("get.id",0,'intval');
        $paper=$this->paper_model->where("id=$id")->find();
        $terms = $this->terms_model->order(array("listorder"=>"asc"))->select();
        $term_id = $paper['paper_term'];
        $term=$this->terms_model->where(array('term_id'=>$term_id))->find();
        $this->_getTermTree(array($term_id));        
        $this->assign("paper",$paper);
        $this->assign("paper_type",$paper['paper_type']);
        $this->assign("paper_setting",unserialize($paper['paper_setting']));
        $this->assign("term",$term);
        $this->assign("terms",$terms);
        $this->display();
    }
    
    // 文章编辑提交
    public function edit_paper(){
        if (IS_POST) {
            if(empty($_POST['paper_name'])){
                $this->error("请填写试卷名称！");
            }
            $count=$this->paper_model->where("id<>%d and paper_name='%s'",I("id"),$_POST['paper_name'])->count();
            if($count){
                $this->error("试卷名称已存在，请修改后重试！");
            }
            
            if(empty($_POST['paper_term'])){
                $this->error("请至少选择一个分类！");
            }
            if(empty($_POST['paper_score'])){
                $this->error("请填写试卷总分！");
            }
            if(empty($_POST['paper_pass_score'])){
                $this->error("请填写通过分数！");
            }
            $data['id']=I("id");
            $data['paper_name']=I("paper_name");
            $data['paper_type']=I("paper_type");
            $data['paper_term']=I("paper_term",0,'intval');
            $data['paper_judge_type']=I("paper_judge_type",0,'intval');
            $data['paper_choose_type']=I("paper_choose_type",0,'intval');                        
            $data['paper_status']=I("paper_status",0,'intval');
            $start_time_array=I("paper_start_time");
            $date=strtotime($start_time_array['day']);
            $start_time=mktime($start_time_array['hour'],$start_time_array['min'],0,date('m',$date),date('d',$date),date('Y',$date));
            //$data['paper_start_time']=date('Y-m-d h:i:s',$start_time);
            //$data['paper_duration']=I("paper_duration",0,'intval');
            $data['paper_score']=I("paper_score",0,'intval');
            $data['paper_pass_score']=I("paper_pass_score",0);
            $paper_setting=is_array(I("paper_setting"))?I("paper_setting"):I("paper_setting");
            $data['listorder']=I("listorder",0,'intval');
            $data['paper_source']=I("paper_source",0);
            $data['paper_modified']=date("Y-m-d H:i:s",time());
            $data['user_id']=get_current_admin_id();
            
            $full_score=0;
            foreach ($this->question_types as $ques_type=>$ques_type_name){
                $full_score+=$paper_setting['questype'][$ques_type]['number']*$paper_setting['questype'][$ques_type]['score'];
                //$data['paper_setting']['questype'][$ques_type]['describe']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$ques_type]['easynumber']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$ques_type]['middlenumber']||$this->error('请填写'.$type.'数量！');
                //$data['paper_setting']['questype'][$ques_type]['hardnumber']||$this->error('请填写'.$type.'数量！');
            }
            //var_dump($paper_setting);
            $full_score!=$data['paper_score']&&$this->error('题目设置分数与总分不一致，请认真填写 ！');
        
            $data['paper_setting']=is_array(I("paper_setting"))?serialize(I("paper_setting")):I("paper_setting");
            $result=$this->paper_model->save($data);
            //echo $this->paper_model->getLastSql();
            $this->success("编辑成功！");
        }
    }
    
    // 文章排序
    public function sorts() {
        $status = parent::_sorts($this->term_relationships_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
    
    /**
     * 文章列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $term_id=I('request.term_id',0,'intval');
        //$paper_type=I('paper_type',0,'intval');
        
        if(!empty($term_id)){
            $where['paper_term']=$term_id;
            $term=$this->paper_model->where(array('paper_term'=>$term_id))->find();
            $this->assign("term",$term);
        }
        //$where['paper_type']=$paper_type;
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['paper_date']=array(
                array('EGT',$start_time)
            );
        }
    
        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['paper_date'])){
                $where['paper_date']=array();
            }
            array_push($where['paper_date'], array('ELT',$end_time));
        }
    
        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['paper_name']=array('like',"%$keyword%");
        }
        	
        $this->paper_model
        ->alias("a")
        ->where($where);
    
        if(!empty($term_id)){
            $this->paper_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
    
        $count=$this->paper_model->count();
        	
        $page = $this->page($count, 20);
        	
        $this->paper_model
        ->alias("a")
        ->join("__USERS__ c ON a.user_id = c.id")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.paper_date DESC");
        if(empty($term_id)){
            $this->paper_model->field('a.*,c.user_login,c.user_nicename');
        }else{
            $this->paper_model->field('a.*,c.user_login,c.user_nicename,b.listorder,b.tid');
            $this->paper_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
        }
        $posts=$this->paper_model->select();
        foreach ($posts as &$post){
            //var_dump($post);
            $post['paper_choose_type']=($post['paper_choose_type']=='0'?'随机选题':'手动选题');
            $post['paper_judge_type']=($post['paper_judge_type']=='0'?'电脑评卷':'教师评卷');
        }
        //echo $this->paper_model->getLastSql();
        
        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);
    }
       
    // 获取文章分类树结构 select 形式
    private function _getTree(){
        $term_id=empty($_REQUEST['term_id'])?6:intval($_REQUEST['term_id']);
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 获取文章分类树结构
    private function _getTermTree($term=array()){
        $result = $this->terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }
    
    // 文章删除
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->paper_model->where(array('id'=>$id))->save(array('paper_status'=>3)) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            	
            if ($this->paper_model->where(array('id'=>array('in',$ids)))->save(array('paper_status'=>3))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
    
    // 文章审核
    public function check(){
        if(isset($_POST['ids']) && $_GET["check"]){
            $ids = I('post.ids/a');
            	
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('paper_status'=>1)) !== false ) {
                $this->success("审核成功！");
            } else {
                $this->error("审核失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["uncheck"]){
            $ids = I('post.ids/a');
    
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('paper_status'=>0)) !== false) {
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }
    }
    
    // 文章置顶
    public function top(){
        if(isset($_POST['ids']) && $_GET["top"]){
            $ids = I('post.ids/a');
            	
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>1))!==false) {
                $this->success("置顶成功！");
            } else {
                $this->error("置顶失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["untop"]){
            $ids = I('post.ids/a');
    
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>0))!==false) {
                $this->success("取消置顶成功！");
            } else {
                $this->error("取消置顶失败！");
            }
        }
    }
    
    // 文章推荐
    public function recommend(){
        if(isset($_POST['ids']) && $_GET["recommend"]){
            $ids = I('post.ids/a');
            	
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["unrecommend"]){
            $ids = I('post.ids/a');
    
            if ( $this->paper_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }
    
    // 文章批量移动
    public function move(){
        if(IS_POST){
            if(isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])){
                $old_term_id=I('get.old_term_id',0,'intval');
                $term_id=I('post.term_id',0,'intval');
                if($old_term_id!=$term_id){
                    $ids=explode(',', I('get.ids/s'));
                    $ids=array_map('intval', $ids);
    
                    foreach ($ids as $id){
                        $this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$old_term_id))->delete();
                        $find_relation_count=$this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$term_id))->count();
                        if($find_relation_count==0){
                            $this->term_relationships_model->add(array('object_id'=>$id,'term_id'=>$term_id));
                        }
                    }
                     
                }
                 
                $this->success("移动成功！");
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->paper_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
    // 文章批量复制
    public function copy(){
        if(IS_POST){
            if(isset($_GET['ids']) && isset($_POST['term_id'])){
                $ids=explode(',', I('get.ids/s'));
                $ids=array_map('intval', $ids);
                $uid=sp_get_current_admin_id();
                $term_id=I('post.term_id',0,'intval');
                $term_count=$paper_model=M('Terms')->where(array('term_id'=>$term_id))->count();
                if($term_count==0){
                    $this->error('分类不存在！');
                }
                 
                $data=array();
                 
                foreach ($ids as $id){
                    $find_post=$this->paper_model->field('paper_keywords,paper_source,paper_content,paper_title,paper_excerpt,smeta')->where(array('id'=>$id))->find();
                    if($find_post){
                        $find_post['user_id']=$uid;
                        $find_post['paper_date']=date('Y-m-d H:i:s');
                        $find_post['paper_modified']=date('Y-m-d H:i:s');
                        $paper_id=$this->paper_model->add($find_post);
                        if($paper_id>0){
                            array_push($data, array('object_id'=>$paper_id,'term_id'=>$term_id));
                        }
                    }
                }
                 
                if ( $this->term_relationships_model->addAll($data) !== false) {
                    $this->success("复制成功！");
                } else {
                    $this->error("复制失败！");
                }
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->paper_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
    // 文章回收站列表
    public function recyclebin(){
        $this->_lists(array('paper_status'=>array('eq',3)));
        $this->_getTree();
        $this->display();
    }
    
    // 清除已经删除的文章
    public function clean(){
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status=$this->paper_model->where(array("id"=>array('in',$ids),'paper_status'=>3))->delete();
            $this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
            	
            if ($status!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }else{
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                $status=$this->paper_model->where(array("id"=>$id,'paper_status'=>3))->delete();
                $this->term_relationships_model->where(array('object_id'=>$id))->delete();
    
                if ($status!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }
    
    // 文章还原
    public function restore(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->paper_model->where(array("id"=>$id,'paper_status'=>3))->save(array("paper_status"=>"1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }
    
}